#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>

#include "mynet/RPop3Client.h"
#include "mynet/RSocketIO.h"
#include "mynet/RSSLSocketIO.h"
#include "mynet/RPop3Message.h"
#include "mynet/RMIMEPart.h"
#include "mynet/RBase64.h"

using namespace std;


int main(int argc, char *argv[])
{
#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32)
  InitSockDLL();
#endif
  fstream log("/home/rui/projects/network/saveattachment/a.log",ios::out|ios::app);
  // read from stdin
  string buf,s;
  getline(cin,s);
  while(! cin.fail())
    {
      buf.append(s);
      buf.append("\r\n");
      log<<s<<endl;
      getline(cin,s);
    }
  //  string buf((istreambuf_iterator<char>(cin)),istreambuf_iterator<char>());
  log<<"get message from stdin finished"<<endl;

  RPop3Message pop3mess;
  pop3mess.Message()=buf;
  {
    log<<"Subject:"<<pop3mess.subject()<<endl;
    log<<"Content-Type:"<<pop3mess.ContentType()<<endl;
    log<<"Message-ID:"<<pop3mess.MessageID()<<endl;
    log<<"Reply-To:"<<pop3mess.ReplyTo()<<endl;
    RMIMEPart mimepart;
    mimepart.Message()=pop3mess.FirstMIMEPart();

    log<<"name of MIME part 1: ["<<mimepart.name()<<" [ file name: "<<mimepart.filename()<<endl;
    log<<"type of MIME part 1: ["<<mimepart.type()<<endl;
    log<<"Write the MIME part : "<<mimepart.save()<<endl;
    int count=1;
    do
      {
	mimepart.Message()=pop3mess.NextMIMEPart();
	count++;
	log<<"name of Mime Part next: ["<<mimepart.name()<<" [ file name: "<<mimepart.filename()<<endl;
	log<<"type of Mime Part next: ["<<mimepart.type()<<endl;
	log<<"Write the MIME part : "<<mimepart.save()<<endl;
      } while (mimepart.Message().length());
    log<<"total parts: "<<count<<endl;
  }

#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32)
  CleanSockDll();
  system("PAUSE");
#endif
  return EXIT_SUCCESS;
}
